<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="css/dialog.css">
    <style>
        body {
            text-align: center;
        }
    </style>
</head>

<body>
    <div style="cursor:pointer;width:30%;height:50px;background:red;margin:0 auto;color:white;line-height:50px;" class="clickMe">点击上传头像图片</div>
   
    <form style="display:none" action="/index.php/index/index/getFace" enctype="multipart/form-data" method="post">
        <p>
            <input type="file" name="pic" accept="image/*">
        </p>
        <p>
            <input class="btn" type="button" value="ajax提交">
        </p>
    </form>
    <canvas id="myCanvas"></canvas>

    <div style="margin:5px;">
        <button style="opacity:0;height:30px;" class="checkBtn">确认裁剪</button>
    </div>
    <img class="finalImg" style="margin-top:15px">
    
    <script src="js/jquery-2.1.0.js"></script>
    <script src="js/touch-0.2.14.min.js"></script>
    <script src="js/vconsole.min.js"></script>
    <script src="js/dialog.min.js"></script>
    <script src="js/exif.js"></script>
    <script src="js/utils.js"></script>
    <script>
        $("body").on("touchmove", function (e) {
            e.preventDefault();
        })
        //上传的div
        $(".clickMe").on("click", function () {
            $("[type=file]").trigger("click");

        })
        //input框的改变
        var canvasOriRotate;
        $("[type=file]").on("change", function () {
            var file = document.querySelector('[type=file]');
            getExif(file, function (e) {
                console.log(e);
                canvasOriRotate = e.needRotation; //deg
            });
            $(".btn").trigger("click");
            loadDialog = $(document).dialog({
                type: 'toast',
                infoIcon: 'img/icon/loading.gif',
                infoText: '正在加载中',
                autoClose: 0
            });
        })
        //开始上传图片，以识别脸部
        $(".btn").on("click", function () {
            var file = document.querySelector('[type=file]');
            var formData = new FormData();
            // 将文件转二进制
            formData.append('pic', file.files[0]);
            formData.append("winW", window.innerWidth);
            $.ajax({
                url: '/index.php/index/index/getFacePos',
                type: 'POST',
                data: formData, // 上传formdata封装的数据
                dataType: 'JSON',
                cache: false, // 不缓存
                processData: false, // jQuery不要去处理发送的数据
                contentType: false, // jQuery不要去设置Content-Type请求头
                success: function (res) { //成功回调
                    console.log(res);
                    /**
                    res.res -1 未上传图片
                            0  未识别到人脸
                            1  正常识别人脸
                    */
                    if (res.res == 1) {
                        appCanvas(res.data.url, res.data.pos, 0, 0.3); //y轴方向矫正0.3倍的height
                    } else if (res.res == 0) {
                        // alert("未识别到人脸");
                        var facePos = {
                            left: 0,
                            top: 0,
                            width: res.data.size["0"],
                            height: res.data.size["1"],
                        }
                        appCanvas(res.data.url, facePos, 0, 0);
                    } else {
                        alert("未上传图片");
                    }
                }
            });
        })

        function appCanvas(imgUrl, facePos, offsetX, offsetY) {
            var winW = window.innerWidth;
            var myCanvas = document.getElementById('myCanvas');
            myCanvas.width = winW * .7;
            myCanvas.height = winW * .7;
            var myCanW = myCanvas.width;
            var myCanH = myCanvas.height;
            var r = myCanW / 4;
            if (!myCanvas || !myCanvas.getContext) {
                return
            };
            var ctx = myCanvas.getContext("2d");

            //开始绘制
            drawScreen()

            function drawScreen() {
                var toLoadImg = new Image();
                toLoadImg.addEventListener("load", function () {
                    //第一次进来时的位置
                    finX = lastX = -(facePos.left + facePos.width / 2);
                    finY = lastY = -(facePos.top + facePos.height / 2);
                    ratio = lastScale = 1;
                    rotate = lastRotate = canvasOriRotate ? canvasOriRotate : 0; //deg
                    onImageReady(lastX, lastY, lastScale, lastRotate);
                })
                // toLoadImg.src = "src/img/1.jpg";
                toLoadImg.src = imgUrl;

                function onImageReady(startX, startY, scale, rotate) {
                    $(".checkBtn").css("opacity","1");
                    loadDialog.close();
                    ctx.clearRect(0, 0, myCanW, myCanH);
                    ctx.save();
                    ctx.beginPath();
                    ctx.fillStyle = "rgba(255,255,255,.6)";
                    ctx.lineWidth = 10;
                    ctx.fillRect(0, 0, myCanW, myCanH);
                    ctx.strokeRect(0, 0, myCanW, myCanH);
                    ctx.restore();
                    ctx.save();
                    ctx.globalCompositeOperation = "destination-out";
                    ctx.beginPath();
                    ctx.translate(myCanW / 2, myCanH / 2);
                    ctx.fillStyle = "green";
                    // ctx.arc(0, 0, r, 0, 2 * Math.PI);
                    ParamEllipse(ctx, 0, 0, r, 1.2* r);
                    ctx.fill();

                    ctx.restore();
                    ctx.save();
                    var imgWidth = toLoadImg.width;
                    var imgHeight = toLoadImg.height;
                    ctx.globalCompositeOperation = "destination-over";

                    ctx.translate(myCanW / 2, myCanH / 2); //把坐标点移动到画布中间
                    ctx.scale(scale, scale);
                    ctx.rotate(rotate / 180 * Math.PI);

                    ctx.drawImage(toLoadImg, 0, 0, imgWidth, imgHeight, startX + facePos.width * offsetX, startY +
                        facePos.height * offsetY, imgWidth, imgHeight);
                    ctx.restore(); //必须
                    ctx.save();
                }
                //移动端事件
                var lastX = lastY = finX = finY = 0,
                    rotate = lastRotate = 0,
                    ratio = lastScale = 1;
                touch.on(myCanvas, "drag", function (e) {
                    console.log("drag", Math.atan2(e.y, e.x) * 180 / Math.PI);
                    var moveRotate = Math.atan2(e.y, e.x);
                    //计算除canvas旋转后与手势滑动的夹角
                    var relativeRotate = rotate / 180 * Math.PI - moveRotate;
                    // finX = lastX + e.distanceX;
                    // finY = lastY + e.distanceY;
                    finX = lastX + e.distance * Math.cos(relativeRotate);
                    finY = lastY - e.distance * Math.sin(relativeRotate);
                    onImageReady(finX, finY, ratio, rotate);
                })
                touch.on(myCanvas, "dragend", function (e) {
                    lastX = finX;
                    lastY = finY;
                    console.log("dragend", lastX, lastY);
                })
                //缩放与旋转
                touch.on(myCanvas, "pinch", function (e) {
                    console.log("pinch", e)
                    ratio = lastScale * e.scale;
                    rotate = lastRotate + e.rotation;
                    onImageReady(finX, finY, ratio, rotate);
                })
                touch.on(myCanvas, "pinchend", function () {
                    console.log("pinchend", ratio);
                    lastScale = ratio;
                    lastRotate = rotate;
                })
                //裁剪按钮
                $(".checkBtn").on("click", function () {
                    var temImgUrl = myCanvas.toDataURL();
                    var temCanvas = document.createElement("canvas");
                    temCanvas.width = 2 * r + 4;
                    // temCanvas.height = 2 * r;
                    temCanvas.height = 2.4 * r + 4;

                    var temImg = new Image();
                    temImg.onload = function () { 
                        var temCtx = temCanvas.getContext("2d");
                        temCtx.beginPath();
                        // temCtx.translate(r, r);
                        temCtx.translate(r+2, 1.2*r+2);
                        // temCtx.arc(0, 0, r, 0, 2 * Math.PI);
                        ParamEllipse(temCtx, 0, 0, r, 1.2 * r);
                        temCtx.clip();
                        temCtx.drawImage(temImg, 0, 0, temImg.width, temImg.height, -myCanW / 2, -myCanH /
                            2, temImg.width, temImg.height);
                        var finalImgUrl = temCanvas.toDataURL();
                        $(".finalImg").attr("src", finalImgUrl);

                    }
                    temImg.src = temImgUrl;
                })
            }
        }

        function ParamEllipse(context, x, y, a, b) {
            //max是等于1除以长轴值a和b中的较大者
            //i每次循环增加1/max，表示度数的增加
            //这样可以使得每次循环所绘制的路径（弧线）接近1像素
            var step = (a > b) ? 1 / a : 1 / b;
            context.beginPath();
            context.moveTo(x + a, y); //从椭圆的左端点开始绘制
            for (var i = 0; i < 2 * Math.PI; i += step) {
                //参数方程为x = a * cos(i), y = b * sin(i)，
                //参数为i，表示度数（弧度）
                context.lineTo(x + a * Math.cos(i), y + b * Math.sin(i));
            }
            context.closePath();
            // context.stroke();
        };
    </script>
</body>

</html>